package com.example.demo.Impl;

import com.example.demo.dto.MbtiSubmitDTO;
import com.example.demo.entity.MbtiResult;
import com.example.demo.entity.Student;
import com.example.demo.entity.TestRecord;
import com.example.demo.repository.MbtiResultRepository;
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.TestRecordRepository;
import com.example.demo.service.MbtiResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class MbtiResultServiceImpl implements MbtiResultService {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TestRecordRepository testRecordRepository;

    @Autowired
    private MbtiResultRepository mbtiResultRepository;

    @Override
    public void submitResult(MbtiSubmitDTO dto) {
        // 获取学生信息
        Student student = studentRepository.findById(dto.getStudentId())
                .orElseThrow(() -> new RuntimeException("学生不存在"));

        // 保存到 test_record（测试记录表）
        TestRecord record = new TestRecord();
        record.setStudent(student);
        record.setResult(dto.getType());
        record.setTestTime(LocalDateTime.now());
        testRecordRepository.save(record);

        // 保存或更新到 mbti_result（最新 MBTI 测试结果表）
        MbtiResult result = mbtiResultRepository.findByStudentId(student.getId())
                .orElse(new MbtiResult());

        result.setStudentId(student.getId());
        result.setClassId(student.getClazz().getId());
        result.setMbtiType(dto.getType());
        result.setType(dto.getType()); // 这里你也可以存维度字符串
        result.setTestTime(LocalDateTime.now());
        result.setCreateTime(LocalDateTime.now());

        mbtiResultRepository.save(result); // insert 或 update
    }

    @Override
    public void saveTestRecord(MbtiSubmitDTO dto) {
        // 如有额外记录需求（如 test_answer 表），可在此实现
    }
}
